package com.pactera.asmp.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.pactera.asmp.server.common.constants.OccupyStatus;
import com.pactera.asmp.server.common.constants.TaskStatus;
import com.pactera.asmp.server.common.websocket.SocketUtil;
import com.pactera.asmp.server.common.websocket.WebSocketServerScreen;
import com.pactera.asmp.server.dao.*;
import com.pactera.asmp.server.entity.*;
import com.pactera.asmp.server.pojo.*;
import com.pactera.asmp.server.utils.AssertUtil;
import com.pactera.asmp.server.utils.PageDataResult;
import com.pactera.asmp.server.vo.ScreenTaskInfo;
import lombok.extern.slf4j.Slf4j;

import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ScreenDataServiceImpl implements  ScreenDataService {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private TestReportMapper testReportMapper;

    @Autowired
    private ProjectModuleMapper projectModuleMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private IssueMapper issueMapper;

    @Autowired
    private IRedisService redisService;

    @Autowired
    @Lazy
    private SocketUtil socketUtil;

    @Autowired
    @Lazy
    private ScreenDataService screenDataService;

    private final static String NOT_NULL_PROJECT_ID = "项目ID不允许为空";
    private final static int REDIS_CACHE_EXPIRE = 60*60*8;  // 8小时
    public static final String REDIS_KEY_SCREEN_TASKCATEGORYDATABYPROJECTID = "SCREEN_TASKCATEGORYDATABYPROJECTID";
    public static final String REDIS_KEY_SCREEN_TASKFAILDATABYPROJECTID = "SCREEN_TASKFAILDATABYPROJECTID";
    public static final String REDIS_KEY_SCREEN_TASKINGBYPROJECTID = "SCREEN_TASKINGBYPROJECTID";
    public static final String REDIS_KEY_SCREEN_ISSUECHARTLINEBYPROJECTID = "SCREEN_ISSUECHARTLINEBYPROJECTID";
    public static final String REDIS_KEY_SCREEN_ISSUECHARTBARBYPROJECTID = "SCREEN_ISSUECHARTBARBYPROJECTID";
    public static final String REDIS_KEY_SCREEN_ISSUEPROCESSNAMEBYPROJECTID = "SCREEN_ISSUEPROCESSNAMEBYPROJECTID";


    @Override
    public List<TaskReportChartVO> getTaskCategoryDataByProjectId(Integer projectId) {
        if(projectId == null) return null;

        String cacheData = redisService.get(REDIS_KEY_SCREEN_TASKCATEGORYDATABYPROJECTID+":"+projectId);
        if(!StringUtils.isEmpty(cacheData)){
            try {
                return JSON.parseObject(cacheData, new TypeReference<List<TaskReportChartVO>>() {});
            }catch (Exception e){
               log.info(e.getMessage());
            }
        }

        List<Integer> scriptIds = this.getScriptIdsByProjectId(projectId);
        if(CollectionUtils.isEmpty(scriptIds)) return null;

        List<ScriptInfo> scriptList = this.testReportMapper.getScriptsByIds(scriptIds);
        if(!CollectionUtils.isEmpty(scriptIds) && !CollectionUtils.isEmpty(scriptList)){
            List<TaskReportChartVO> data = new ArrayList<>();
            Map<String,Integer> map1 = new HashMap<>();
            for(int i=0;i<scriptIds.size();i++){
                for (int j = 0; j < scriptList.size() ; j++) {
                    if(scriptIds.get(i).intValue() == scriptList.get(j).getId().intValue()){
                        // 找到脚本
                        if(!map1.containsKey(scriptList.get(j).getScriptCategory())){
                            map1.put(scriptList.get(j).getScriptCategory(),1);
                        }
                        else{
                            map1.put(scriptList.get(j).getScriptCategory(),map1.get(scriptList.get(j).getScriptCategory())+1);
                        }
                        break;
                    }
                }
            }
            for (Map.Entry<String, Integer> entry : map1.entrySet()) {
                data.add(new TaskReportChartVO(entry.getKey(),entry.getValue()));
            }
            if(!CollectionUtils.isEmpty(data)) {
                redisService.setex(REDIS_KEY_SCREEN_TASKCATEGORYDATABYPROJECTID+":"+projectId, JSON.toJSONString(data)
                    , TimeUnit.SECONDS, redisService.getExpire(REDIS_CACHE_EXPIRE, 60));
            }
            return data;
        }
        return null;
    }
    private List<Integer> getScriptIdsByProjectId(Integer projectId) {
        List<String> scriptIds = testReportMapper.getScriptIdsByProjectId(projectId);
        if(CollectionUtils.isEmpty(scriptIds)) return new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        transIds(scriptIds,ids);
        return ids;
    }
    private void transIds(List<String> scriptIds, List<Integer> ids){
        if(CollectionUtils.isEmpty(scriptIds)) return;
        String[] tmp;
        for(String id : scriptIds){
            if(StringUtils.isEmpty(id)) continue;
            tmp = id.split(",");
            for(String a :tmp){
                ids.add(Integer.parseInt(a));
            }
        }
    }

    @Override
    public List<TaskReportChartVO> getTaskFailDataByProjectId(Integer projectId) {
        if(projectId == null) return null;

        String cacheData = redisService.get(REDIS_KEY_SCREEN_TASKFAILDATABYPROJECTID+":"+projectId);
        if(!StringUtils.isEmpty(cacheData)){
            try {
                return JSON.parseObject(cacheData, new TypeReference<List<TaskReportChartVO>>() {});
            }catch (Exception e){
                log.info(e.getMessage());
            }
        }
        List<TaskFailCount> taskFailCountList = this.testReportMapper.getTaskFailCountListByProjectId(projectId);
        if(CollectionUtils.isEmpty(taskFailCountList)) return null;

        ProjectModuleSearch search = new ProjectModuleSearch();
        search.setProjectId(projectId);
        List<ProjectModuleDTO> moduleList = projectModuleMapper.select(search);
        if(CollectionUtils.isEmpty(moduleList)) return null;

        List<TaskReportChartVO> data = new ArrayList<>();
        for(TaskFailCount task : taskFailCountList){
            TaskReportChartVO d = new TaskReportChartVO();
            d.setCount(task.getCount());
            d.setItem("");
            data.add(d);
            for(ProjectModuleDTO module : moduleList){
                if(task.getId().intValue() == module.getId().intValue()){
                    d.setItem(module.getName());
                    break;
                }
            }
        }
        if(!CollectionUtils.isEmpty(data)) {
            redisService.setex(REDIS_KEY_SCREEN_TASKFAILDATABYPROJECTID+":"+projectId, JSON.toJSONString(data)
                    , TimeUnit.SECONDS, redisService.getExpire(REDIS_CACHE_EXPIRE, 60));
        }
        return data;
    }

    @Override
    public PageDataResult getTaskingByProjectId(TaskSearchDTO taskSearchDTO) {
        if(taskSearchDTO == null || taskSearchDTO.getProjectId() == null) return null;

        PageDataResult pageDataResult = new PageDataResult();
        if (null == taskSearchDTO.getPageNum() || taskSearchDTO.getPageNum().intValue() == 0) {
            taskSearchDTO.setPageNum(1);
        }
        if (null == taskSearchDTO.getPageSize() || taskSearchDTO.getPageSize().intValue() == 0) {
            taskSearchDTO.setPageSize(10);
        }

        if(taskSearchDTO.getPageNum().intValue() < 0 || taskSearchDTO.getPageSize().intValue() < 0) {
            pageDataResult.setTotals(0);
            pageDataResult.setList(Lists.newArrayList());
            return pageDataResult;
        }
        PageHelper.startPage(taskSearchDTO.getPageNum(), taskSearchDTO.getPageSize());

        List<TaskExeingDTO> taskExeingList = this.taskMapper.getTaskExeingByProjectId(taskSearchDTO.getProjectId());
        if(CollectionUtils.isEmpty(taskExeingList)) return null;
        PageInfo<TaskExeingDTO> pageInfo = new PageInfo<>(taskExeingList);
        pageDataResult.setTotals(Long.valueOf(pageInfo.getTotal()).intValue());
        pageDataResult.setList(taskExeingList);
        return pageDataResult;
    }

    @Override
    public List<IssueChartVO> getIssueChartLineByProjectId(Integer projectId) {
        if(projectId == null) return null;

        String cacheData = redisService.get(REDIS_KEY_SCREEN_ISSUECHARTLINEBYPROJECTID+":"+projectId);
        if(!StringUtils.isEmpty(cacheData)){
            try {
                return JSON.parseObject(cacheData, new TypeReference<List<IssueChartVO>>() {});
            }catch (Exception e){
                log.info(e.getMessage());
            }
        }

        ProjectInfo projectInfo = this.projectMapper.selectByPrimaryKey(projectId);
        if(projectInfo == null || StringUtils.isEmpty(projectInfo.getProjectName())) return  null;
        List<IssueChartVO> list = this.issueMapper.getIssueChartLineByProject(projectInfo.getProjectName());

        fillIssueChaartData(list);
        if(!CollectionUtils.isEmpty(list)) {
            redisService.setex(REDIS_KEY_SCREEN_ISSUECHARTLINEBYPROJECTID+":"+projectId, JSON.toJSONString(list)
                    , TimeUnit.SECONDS, redisService.getExpire(REDIS_CACHE_EXPIRE, 60));
        }
        return list;
    }

    private void fillIssueChaartData(List<IssueChartVO> data){
        if(CollectionUtils.isEmpty(data)) return;
        List<String> item1All = new ArrayList<>();
        List<String> item2All = new ArrayList<>();
        List<IssueChartVO> toAdd = new ArrayList<>();
        for(IssueChartVO vo : data){
            if(!item1All.contains(vo.getItem1())) item1All.add(vo.getItem1());
            if(!item2All.contains(vo.getItem2())) item2All.add(vo.getItem2());
        }

        for (String item1 : item1All){
            for (String item2 : item2All){
                if(!exist(item1,item2,data)){
                    toAdd.add(new IssueChartVO(item1,item2,0));
                }
            }
        }
        if(!CollectionUtils.isEmpty(toAdd)) {
            data.addAll(toAdd);
        }

        // data 先根据item1升序，再根据item2升序
        Comparator<IssueChartVO> item1Sort = Comparator.comparing(IssueChartVO :: getItem1);
        Comparator<IssueChartVO> item2Sort = Comparator.comparing(IssueChartVO :: getItem2);
        Collections.sort(data, item1Sort.thenComparing(item2Sort));
    }

    private boolean exist(String item1,String item2,List<IssueChartVO> data){
        for (IssueChartVO vo : data){
            if(item1.equalsIgnoreCase(vo.getItem1()) && item2.equalsIgnoreCase(vo.getItem2())){
                return true;
            }
        }
        return false;
    }

    @Override
    public List<IssueChartVO> getIssueChartBarByProjectId(Integer projectId) {
        if(projectId == null) return null;

        String cacheData = redisService.get(REDIS_KEY_SCREEN_ISSUECHARTBARBYPROJECTID+":"+projectId);
        if(!StringUtils.isEmpty(cacheData)){
            try {
                return JSON.parseObject(cacheData, new TypeReference<List<IssueChartVO>>() {});
            }catch (Exception e){
                log.info(e.getMessage());
            }
        }

        ProjectInfo projectInfo = this.projectMapper.selectByPrimaryKey(projectId);
        if(projectInfo == null || StringUtils.isEmpty(projectInfo.getProjectName())) return  null;

        List<IssueChartVO> list = this.issueMapper.getIssueChartBarByProject(projectInfo.getProjectName());
        fillIssueChaartData(list);
        if(!CollectionUtils.isEmpty(list)) {
            redisService.setex(REDIS_KEY_SCREEN_ISSUECHARTBARBYPROJECTID+":"+projectId, JSON.toJSONString(list)
                    , TimeUnit.SECONDS, redisService.getExpire(REDIS_CACHE_EXPIRE, 60));
        }
        return list;
    }

    @Override
    public void taskChanged(Integer projectId) {
        redisService.remove(REDIS_KEY_SCREEN_TASKCATEGORYDATABYPROJECTID+":"+projectId);
        redisService.remove(REDIS_KEY_SCREEN_TASKFAILDATABYPROJECTID+":"+projectId);
        screenDataService.asyncGetTaskCategoryDataByProjectId(projectId);
        screenDataService.asyncGetTaskFailDataByProjectId(projectId);

        TaskSearchDTO searchDTO = new TaskSearchDTO();
        searchDTO.setProjectId(projectId);
        screenDataService.asyncGetTaskingByProjectId(searchDTO);
    }

    @Override
    public void taskChangedStatus(String msgCode, Integer projectId, Object taskIdOrPercent) {
        redisService.remove(REDIS_KEY_SCREEN_TASKCATEGORYDATABYPROJECTID+":"+projectId);
        redisService.remove(REDIS_KEY_SCREEN_TASKFAILDATABYPROJECTID+":"+projectId);
        this.asynGetTaskChangedStatus(msgCode,projectId,taskIdOrPercent);
    }

    @Override
    public void issueChanged(Integer projectId) {
        redisService.remove(REDIS_KEY_SCREEN_ISSUECHARTLINEBYPROJECTID+":"+projectId);
        redisService.remove(REDIS_KEY_SCREEN_ISSUECHARTBARBYPROJECTID+":"+projectId);
        redisService.remove(REDIS_KEY_SCREEN_ISSUEPROCESSNAMEBYPROJECTID+":"+projectId);
        screenDataService.asyncGetIssueChartLineByProjectId(projectId);
        screenDataService.asyncGetIssueChartBarByProjectId(projectId);
    }


    @Async
    @Override
    public void asyncGetTaskCategoryDataByProjectId(Integer projectId) {
        if(Boolean.FALSE.equals(projcetOnFocus(projectId))) return;

        List<TaskReportChartVO> taskCategoryDataByProjectId = getTaskCategoryDataByProjectId(projectId);
        sendMessage(taskCategoryDataByProjectId,projectId, WebSocketServerScreen.SCREEN_CODE_DATA_TASKCATEGORY);
    }

    @Async
    @Override
    public void asyncGetTaskFailDataByProjectId(Integer projectId) {
        if(Boolean.FALSE.equals(projcetOnFocus(projectId))) return;

        List<TaskReportChartVO> taskFailDataByProjectId = this.getTaskFailDataByProjectId(projectId);
        sendMessage(taskFailDataByProjectId,projectId,WebSocketServerScreen.SCREEN_CODE_DATA_TASKFAIL);
    }

    @Async
    @Override
    public void asyncGetTaskingByProjectId(TaskSearchDTO taskSearchDTO) {
        if(Boolean.FALSE.equals(projcetOnFocus(taskSearchDTO.getProjectId()))) return;

        List<ScreenTaskInfo> stInfoList = new ArrayList<>();
        if (queryExcTaskInfo(taskSearchDTO.getProjectId(), stInfoList)) return;

        sendMessage(stInfoList, taskSearchDTO.getProjectId(), WebSocketServerScreen.SCREEN_CODE_DATA_TASKING);
    }

    @Async
    @Override
    public void asyncGetIssueChartLineByProjectId(Integer projectId) {
        if(Boolean.FALSE.equals(projcetOnFocus(projectId))) return;

        List<IssueChartVO> issueChartLineByProjectId = getIssueChartLineByProjectId(projectId);
        sendMessage(issueChartLineByProjectId,projectId,WebSocketServerScreen.SCREEN_CODE_DATA_ISSUECHARTLINE);
    }

    @Async
    @Override
    public void asyncGetIssueChartBarByProjectId(Integer projectId) {
        if(Boolean.FALSE.equals(projcetOnFocus(projectId))) return;

        List<IssueChartVO> issueChartBarByProjectId = getIssueChartBarByProjectId(projectId);
        sendMessage(issueChartBarByProjectId,projectId,WebSocketServerScreen.SCREEN_CODE_DATA_ISSUECHARTBAR);
    }

    @Async
    @Override
    public void asynGetTaskChangedStatus(String msgCode, Integer projectId, Object taskIdOrPercent) {
        if(Boolean.FALSE.equals(projcetOnFocus(projectId))) return;
        sendMessage(taskIdOrPercent,projectId,msgCode);
    }

    @Override
    public List<IssueChartVO> getIssueProcessNameByProject(Integer projectId) {
        AssertUtil.notNull(projectId,NOT_NULL_PROJECT_ID);

        String cacheData = redisService.get(REDIS_KEY_SCREEN_ISSUEPROCESSNAMEBYPROJECTID+":"+projectId);
        if(!StringUtils.isEmpty(cacheData)){
            try {
                return JSON.parseObject(cacheData, new TypeReference<List<IssueChartVO>>() {});
            }catch (Exception e){
                log.info(e.getMessage());
            }
        }

        ProjectInfo projectInfo = this.projectMapper.selectByPrimaryKey(projectId);
        if(projectInfo == null || StringUtils.isEmpty(projectInfo.getProjectName())) return  new ArrayList<>();
        List<IssueChartVO> list = this.issueMapper.getIssueProcessNameByProject(projectInfo.getProjectName());

        if(!CollectionUtils.isEmpty(list)) {
            redisService.setex(REDIS_KEY_SCREEN_ISSUEPROCESSNAMEBYPROJECTID+":"+projectId, JSON.toJSONString(list)
                    , TimeUnit.SECONDS, redisService.getExpire(REDIS_CACHE_EXPIRE, 60));
        }
        return list;
    }

    @Override
    public List<ScreenDeviceInfo> getScreenDeviceListByProjectId(Integer projectId) {
        AssertUtil.notNull(projectId, NOT_NULL_PROJECT_ID);
        return this.projectMapper.getScreenDeviceListByProjectId(projectId);
    }

    @Override
    public List<ScreenDeviceInfo> getScreenMasterListByProjectId(Integer projectId) {
        AssertUtil.notNull(projectId,NOT_NULL_PROJECT_ID);
        return this.projectMapper.getScreenMasterListByProjectId(projectId);
    }

    @Override
    public List<ScreenDeviceInfo> getScreenTaskingDeviceListByProjectId(Integer projectId) {
        AssertUtil.notNull(projectId,NOT_NULL_PROJECT_ID);
        return this.projectMapper.getScreenTaskingDeviceListByProjectId(projectId);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String wsDirectExchange = "WsDirectExchange";

    /*@Autowired
    private TaskMapper taskMapper;*/

    @Autowired
    private SubtaskMapper subtaskMapper;

    @Autowired
    private SubtaskDistributeMapper subtaskDistributeMapper;

    @Autowired
    private TaskDeviceMapper taskDeviceMapper;

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Async
    @Override
    public void refreshTaskInfo(String userId, Integer projectId){
        List<ScreenTaskInfo> stInfoList = new ArrayList<>();
        //mock
//        ScreenTaskInfo stiTT = new ScreenTaskInfo();
//        stiTT.setDuid("testduit");
//        stiTT.setPercentage("20%");
//        stiTT.setName("test");
//        stInfoList.add(stiTT);
        //查询projectId的,执行中的taskhistList
        if (queryExcTaskInfo(projectId, stInfoList)) return;
        //发送task执行数据
        sendTaskMsgToScreen(stInfoList, projectId.toString());
    }

    private boolean queryExcTaskInfo(Integer projectId, List<ScreenTaskInfo> stInfoList) {
        List<TaskDTO> taskHistList = taskMapper.queryByProjectIdAndStatus(projectId, TaskStatus.TASK_EXEC.getValue());
        if(CollectionUtils.isEmpty(taskHistList)){
            //已没有执行的task, 刷新大屏
            //生成message的json
            String message = JSONObject.toJSONString(stInfoList);
            //发送task执行数据
            sendTaskMsgToScreen(stInfoList, projectId.toString());
            return true;
        }
        //然后查taskhist的 t_subtask_distribute, 计算进度
        for(TaskDTO th : taskHistList){
            ScreenTaskInfo sti = new ScreenTaskInfo();
            sti.setName(th.getName());
            //然后查taskhist的 t_subtask_distribute, 计算进度
            if (handlePercentForScreenTaskInfo(th, sti)) continue;
            //查t_task_device 得到duid
            if (handleDuidForScreenTaskInfo(th, sti, stInfoList))  continue;
//            stInfoList.add(sti);
        }
        return false;
    }

    private boolean handlePercentForScreenTaskInfo(TaskDTO th, ScreenTaskInfo sti) {
        SubtaskDistributeExample example = new SubtaskDistributeExample();
        example.createCriteria().andTaskIdEqualTo(th.getId().longValue()).andIsDeletedEqualTo(0);
        List<SubtaskDistribute> sdlist = subtaskDistributeMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(sdlist)){
            return true;
        }
        SubtaskDistribute sd = sdlist.get(0);
        if(sd.getExecSum()!=null && sd.getNeedExecSum()!=null && sd.getNeedExecSum()>0){
            sti.setPercentage((100*sd.getExecSum()/sd.getNeedExecSum())+"%");
        }else{
            return true;
        }
        return false;
    }

    private boolean handleDuidForScreenTaskInfo(TaskDTO th, ScreenTaskInfo sti, List<ScreenTaskInfo> stInfoList) {
        //查t_task_device 得到duid
        TaskDeviceExample taskDeviceExample = new TaskDeviceExample();
        taskDeviceExample.createCriteria().andTaskIdEqualTo(th.getId().longValue()).
                andOccupyStatusEqualTo(OccupyStatus.OCCUPIED.getValue()).andIsDeletedEqualTo(0);
        List<TaskDevice> taskDeviceList = taskDeviceMapper.selectByExample(taskDeviceExample);
        if(CollectionUtils.isEmpty(taskDeviceList)){
            return true;
        }
//        sti.setDuid("");
        for(TaskDevice td:taskDeviceList){
            ScreenTaskInfo screenTaskInfo = new ScreenTaskInfo();
            screenTaskInfo.setName(sti.getName());
            screenTaskInfo.setPercentage(sti.getPercentage());
            String duid = td.getDuid();
            if( ! StringUtils.isEmpty(td.getAuxDuid())){
                duid += ","+ td.getAuxDuid();
            }
            screenTaskInfo.setDuid(duid);
            DeviceInfo deviceInfo = deviceInfoMapper.selectByDuid(td.getDuid());
            screenTaskInfo.setDisplayIds(JSONObject.parseObject(deviceInfo.getDisplayIdsStr(), String[].class));
            stInfoList.add(screenTaskInfo);
        }
//        //去掉逗号
//        sti.setDuid(sti.getDuid().substring(1));
        return false;
    }

    private void sendTaskMsgToScreen(List<ScreenTaskInfo> stInfoList,String projectId){

        sendMessage(stInfoList, Integer.valueOf(projectId), WebSocketServerScreen.SCREEN_CODE_DATA_TASKING);

        //按projectId来取userId
//        String setkey = SocketUtil.REDIS_KEY_SET_SCREEN_PROJECT_SESSION + ":" + projectId;
//        Set<String> sessionKeySet = redisTemplate.opsForSet().members(setkey);
//        for(String sessionKey : sessionKeySet){
//            WSScriptMessage<ScreenTaskInfo> msgContent = new WSScriptMessage<>();
//            msgContent.setTouuid(sessionKey.split("@")[0]);
//            msgContent.setFromuuid("server");
//            msgContent.setMsgcode("908");
//            msgContent.setTaskId(-1);
//            msgContent.setExeNumber(1);
//            msgContent.setList(stInfoList);
//            String content = JSONObject.toJSONString(msgContent);
//            log.info("sessionKey:{}, sendMsgToScreen:{}", sessionKey, content);
//            Session session = WebSocketServerScreen.id2sessionMap.get(sessionKey);
//            try {
//                session.getBasicRemote().sendText(content);
//            } catch (IOException e) {
//                log.error("error",e);
//            }
//            /*try {
//                socketUtil.sendMQ("server", to, content.getBytes("utf-8"), "json", null);
//            }catch (UnsupportedEncodingException e){
//                log.error("error",e);
//            }*/
//        }
    }


    private void sendMessage(Object data,Integer projectId,String msgCode) {
        Set<String> members = redisService.getRedisTemplate().opsForSet().members(SocketUtil.REDIS_KEY_SET_SCREEN_PROJECT_SESSION+":"+projectId);
        WSMessage message = new WSMessage();
        message.setFromuuid("Server");
        message.setMsgcode(msgCode);
        message.setProjectId(projectId);

        if(data == null) data = new ArrayList<>();
        if(data instanceof List){
            message.setList((List) data);
        }
        else {
            message.setList(Arrays.asList(data));
        }
        for(String member : members){
            try {
                message.setTouuid(member.split("@")[0]);
                socketUtil.sendMQ("Serve",member.split("@")[0],objectMapper.writeValueAsBytes(message),"json",null);
            } catch (JsonProcessingException e) {
                log.info(e.getMessage());
            }
        }
    }

    // 是否有大屏用户关注当前项目    是：true   否：false
    private Boolean projcetOnFocus(Integer projectId){
        Set<String> members = redisService.getRedisTemplate().opsForSet().members(SocketUtil.REDIS_KEY_SET_SCREEN_PROJECT_SESSION+":"+projectId);
        return !CollectionUtils.isEmpty(members);
    }
}
